#pragma once
#include <iostream>
#include<string>
#include<unistd.h>
#include<pthread.h>
#include<cstring>
#include<functional>


namespace cls
{
    int num = 1;
    class Pthread
    {
        using func_t = std::function<void()>;
    public:
        Pthread(func_t func,bool joinable = true)
        :_joinable(joinable)
        ,_func(func)
        {
            _name = "pthread-" + std::to_string(num++);
        }

        bool Start()
        {
            int n = pthread_create(&_tid,nullptr,Routine,this); //
            if(n > 0)
            {
                std::cerr << "Start fail : " << strerror(n) <<std::endl;
                return false;   
            }
            if(!_joinable)
            {
                Detach();
            }
            return true;
        }

        bool Stop()
        {
            int n = pthread_cancel(_tid);
            if(n > 0)
            {
                std::cerr << "Stop fail : " << strerror(n) <<std::endl;
                return false;
            }
            std::cout << "stop success " <<std::endl;
            return true;
        }

        bool Join()
        {
            if(_joinable)
            {
                pthread_join(_tid,nullptr);
                return true;
            }
            else
            {
                std::cerr << "线程已经设为分离状态，无需等待" <<std::endl;
                return false;
            }
        }

        ~Pthread()
        {

        }

        bool Detach()
        {
            if(_joinable == false)
            {
                return false;
            }
            _joinable = false;
            pthread_detach(_tid);
            return true;
        }

        static void* Routine(void* args)
        {
            //回调
            Pthread* const self =  static_cast<Pthread* const>(args);
            pthread_setname_np(self->_tid,self->_name.c_str());
            self->_func();
            return nullptr;
        }

    private:
        std::string _name;
        pthread_t _tid;
        bool _joinable;
        func_t _func;
    };


}
